import { message, notification } from 'antd';
import { extend } from 'umi-request';

/* 异常处理 */
const errorHandler = function (error) {
  if (error.response) {
    const { data, status, statusText = '服务器异常' } = error.response;
    if (status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message ?? '无权访问',
      });
    }
    if (status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed',
      });
    }
    if (status === 500) {
      notification.error({
        message: statusText,
      });
    }
  }
  return Promise.reject(error);
};

const request = extend({
  // 为每个请求添加前缀
  prefix: '',
  errorHandler,
  headers: {
    'app-code': 'MOM-SERVICE-APP',
    'app-access-key': 'abc123',
  },
});

/* 处理data */
const handleResponseData = (response) => {
  try {
    const {
      success,
      errMessage = '接口处理异常!',
      code,
      loginPageUrl,
      msg = '接口处理异常!',
    } = response;
    if (!window.location.origin) {
      window.location.origin = `${window.location.protocol}//${window.location.hostname}${
        window.location.port ? `:${window.location.port}` : ''
      }`;
    }
    if (code === -1) {
      message.error(msg);
      return new Error(msg);
    }
    if (code === 501 && loginPageUrl) {
      if (process.env.NODE_ENV !== 'development') {
        setTimeout(() => {
          window.location.href = `${loginPageUrl}${encodeURIComponent(
            `${window.location.origin}`,
          )}`;
        }, 500);
      }
      return new Error(msg ?? '登录超时');
    }
    if (success === false) {
      message.error(errMessage);
      return new Error(errMessage);
    }
  } catch (error) {
    return new Error(error);
  }
  return response;
};

const get = (url = '', params = {}, options = {}) =>
  request.get(url, { ...options, params }).then(handleResponseData);

const post = (url = '', data = {}, options = {}) =>
  request.post(url, { ...options, data }).then(handleResponseData);

const put = (url = '', data = {}, options = {}) =>
  request.put(url, { ...options, data }).then(handleResponseData);

const del = (url = '', data = {}, options = {}) =>
  request.delete(url, { ...options, data }).then(handleResponseData);

export { request, get, post, put, del };
